<?php

namespace app\home\controller;

use app\common\controller\BaseController;
use app\common\model\hfztcy\LibBalanceChangeRecords;
use app\common\model\hfztcy\LibBalanceRecords;
use app\common\model\hfztcy\LibBrowseHistory;
use app\common\model\hfztcy\LibCollect;
use app\common\model\hfztcy\LibCollectCategory;
use app\common\model\hfztcy\LibConfig;
use app\common\model\hfztcy\LibEvaluation;
use app\common\model\hfztcy\LibMember;
use app\common\model\hfztcy\LibMessage;
use app\common\model\hfztcy\LibOrder;
use app\common\model\hfztcy\LibOrderRedMother;
use app\common\model\hfztcy\LibOrderRefund;
use app\common\model\hfztcy\LibOrderVip;
use app\common\model\hfztcy\LibOrderVipAuth;
use app\common\model\hfztcy\LibQuestions;
use app\common\model\hfztcy\LibStore;
use app\common\model\hfztcy\LibStoresApply;
use app\common\model\hfztcy\LibUserVideoAuth;
use app\common\model\hfztcy\LibVideoAuth;
use app\common\model\hfztcy\LibVideoCategory;
use app\common\model\hfztcy\LibVip;
use app\common\model\hfztcy\LibWithdrawalAccounts;
use app\common\model\hfztcy\LibWithdrawalApply;
use app\common\model\LibUser;
use app\common\model\service\LibPoster;
use app\common\model\service\LibStoreLogin;
use app\common\model\service\LibUploadCompressImage;
use common\Common;
use think\Db;
use think\Exception;
use UtilQRcode\UtilQRcode;
use wechatUtil\JsSdk;

/**
 *
 * @name Api.php
 * @package yxys
 * @category controller
 * @link http://www.changekeji.com
 * @author rxy
 * @version 2.0
 * @copyright CHANGE INC
 * @since 2022-06-22
 */
class Api extends BaseController
{
    public $user_id;

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->user_id = input('user_id');
        error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_WARNING);
        parent::__construct();
    }

    public function refund ($a,$b,$d,$c)
    {
        $total_fee = $b;
        $refund_fee = $d;
        // 确认是否已退款
        require_once __DIR__ . "/../../../extend/pay/notify/lib/WxPay.Api.php";

        // 查询退款接口
        $queryInput = new \WxPayRefundQuery();
        $queryInput->SetTransaction_id($a);
        $queryResult = \WxPayApi::refundQuery($queryInput);
        if ($queryResult['result_code'] == 'SUCCESS' && $queryResult['return_code'] == 'SUCCESS') {
            echo json_encode(Common::errorArray(0, '订单已退款', false));
            die();
        }

        // 发起退款
        $input = new \WxPayRefund();
        $input->SetTransaction_id($a);//微信订单号
        $input->SetTotal_fee($total_fee * 100);
        $input->SetRefund_fee($refund_fee * 100);
        $input->SetOut_refund_no($c);//设置退款单号
        $input->SetOp_user_id(\WxPayConfig::MCHID);
        $refundResult = \WxPayApi::refund($input);
        dump($refundResult);
    }

    /**
     * Info: 检查用户
     * Date: 2022/10/17 9:12
     */
    private function checkUser()
    {
        $model = new LibUser();
        return $model->findUser(['id' => $this->user_id]);
    }

    /**
     * 上传图片
     */
    public function uploadImageOld()
    {
        $dir = input('dir', 'hfztcy');
        $file = request()->file('file');
        if ($file) {
            $info = $file->move(ROOT_PATH . 'public' . DS . 'upload/' . $dir);
            if ($info) {
                $name = $info->getSaveName();
                $name = 'upload/' . $dir . DS . $name;
                $this->sendSuccess('上传成功', str_replace('\\', '/', $name));
            } else {
                // 上传失败获取错误信息
                $this->sendFail($file->getError());
            }
        }
    }

    public function uploadImage ()
    {
        $dir = input('dir', 'hfztcy');
        $result = (new LibUploadCompressImage($dir))->setRename()->uploadImage();
        $this->response = $result;
        $this->sendResponse();
    }

    /**
     * 删除上传图片
     */
    public function deleteImage()
    {
        $url = ROOT_PATH . 'public/' . str_replace(ROOT_URL . '/', '', urldecode(input('url')));
        if (file_exists($url)) {
            file_exists(str_replace('_thumb','',$url)) && unlink(str_replace('_thumb','',$url));
            unlink($url);
        }
        $this->sendSuccess('删除成功', true);
    }

    /**
     * Info: 门店登录
     * Date: 2022/11/17 9:12
     */
    public function loginStore ()
    {
        $username = input('username','');
        $password = input('password','');
        $loginRes = (new LibStoreLogin($username,$password))->login();
        if ($loginRes['errorCode'] == 1) $this->sendFail('账号或者密码错误,登录失败');
        // 门店信息
        $storeInfo = $loginRes['data'];
        // 用户信息
        $findMemberRes = (new LibMember())->findMember(['user_id' => $loginRes['data']['uid']]);
        $storeInfo['member'] = $findMemberRes['data'];
        // 绑定的上级
        $userModel = new LibUser();
        $findUserRes = $userModel->findUser(['id' => $loginRes['data']['user_id']]);
        $storeInfo['store_parent_user'] = [];
        if ($findUserRes['errorCode'] == 0) {
            $storeInfo['store_parent_user']['nick_name'] = $findUserRes['data']['nick_name'];
            $storeInfo['store_parent_user']['head_img_url'] = $findUserRes['data']['head_img_url'];
            $storeInfo['store_parent_user']['mobile'] = '';
            $findMemberUserRes = (new LibMember())->findMember(['user_id' => $loginRes['data']['user_id']]);
            if ($findMemberUserRes['errorCode'] == 0) {
                $storeInfo['store_parent_user']['nick_name'] = $findMemberUserRes['data']['username'];
                $storeInfo['store_parent_user']['mobile'] = $findMemberUserRes['data']['mobile'];
            }
        }
        $this->sendSuccess('登录成功',$storeInfo);
    }

    /**
     * Info: 注册
     * Date: 2022/11/8 13:53
     */
    public function registerUser()
    {
        $args = input();
        // 检查用户
        $userRes = $this->checkUser();
        if ($userRes['errorCode'] == 1) $this->sendFail('用户不存在');
        $model = new LibMember();
        $checkRes = $model->goCheck($args);
        $args['photo_list'] = trim($args['photo_list'],',');
        $photo_list = explode(',',$args['photo_list']);
        $photo_list = array_filter($photo_list);
        if (empty($photo_list)) $this->sendFail('请上传个人照片');
        $args['photo_list'] = implode(',',$photo_list);
        $findUserMobileRes = $model->findMember(['mobile' => $args['mobile']]);
        if ($findUserMobileRes['errorCode'] == 0) $this->sendFail('手机号码已存在');
        if ($checkRes['errorCode'] == 1) $this->sendFail($checkRes['errorInfo']);
        $findRes = $model->findMember(['user_id' => $this->user_id]);
        if ($findRes['errorCode'] == 0) {
            if ($findRes['data']['audit_state'] == 0) $this->sendFail('您的资料已提交到平台正在审核中，审核期间无法提交');
            if ($findRes['data']['audit_state'] == 1) $this->sendFail('您的资料审核已通过，不能重复提交');
        }
        $args['identity_id'] = $model->generateMemberID();
        $args['add_time'] = Common::getTime();
        // 同步游客余额字段
        $args['total_balance'] = $userRes['data']['total_balance'];
        $args['balance'] = $userRes['data']['balance'];
        unset($args['isUpdatePhoto']);
        $result = $model->addMember($args);
        $this->sendSuccess('注册成功，等待审核', $result['data']);
    }

    /**
     * Info: 修改用户信息
     * Date: 2022/11/22 14:35
     */
    public function editMemberInfo ()
    {
        $args = input();
        // 检查用户
        $userRes = $this->checkUser();
        if ($userRes['errorCode'] == 1) $this->sendFail('用户不存在');
        $model = new LibMember();
        $checkRes = $model->goCheck($args,'edit');
        if ($checkRes['errorCode'] == 1) $this->sendFail($checkRes['errorInfo']);
        $args['photo_list'] = trim($args['photo_list'],',');
        $photo_list = explode(',',$args['photo_list']);
        $photo_list = array_filter($photo_list);
        if (empty($photo_list)) $this->sendFail('请上传个人照片');
        $args['photo_list'] = implode(',',$photo_list);
        // 判断审核是否不通过
        $msg = '修改成功';
        $findUserRes = $model->findMember(['user_id' => $args['user_id']]);
        if ($findUserRes['errorCode'] == 0) {
            // 删除相册第一张图片
            if ($args['isUpdatePhoto']) {
                $photo_list = explode(',',$findUserRes['data']['photo_list']);
                $photo_index_0 = $photo_list[0];
                $photo_list = array_shift($photo_list);
                $url = ROOT_PATH . 'public/' . str_replace(ROOT_URL . '/', '', urldecode($photo_index_0));
                if (file_exists($url)) {
                    file_exists(str_replace('_thumb','',$url)) && unlink(str_replace('_thumb','',$url));
                    unlink($url);
                }
            }

            //审核驳回，用户修改后，即待审核
            if ($findUserRes['data']['audit_state'] == 2) {
                $args['audit_state'] = 0;
                $args['audit_msg'] = NULL;
                $args['audit_time'] = NULL;
            }
            //用户修改相册
            if ($args['audit_state'] == 0) {
                $args['add_time'] = Common::getTime();
                $msg = '您的修改已提交，请等待审核。';
            }
        }
        unset($args['isUpdatePhoto']);
        $result = $model->updateMember(['user_id' => $args['user_id']],$args);
        $this->sendSuccess($msg, $result['data']);
    }

    /**
     * Info: 会员列表
     * Date: 2022/11/8 14:43
     */
    public function getMemberList()
    {
        $page = $this->getPageInfo();
        $result = (new \app\common\model\service\LibMember())->pagingMemberList(input(),$page);
        $this->response = $result;
        $this->sendResponse();
    }

    /**
     * Info: 用户信息
     * Date: 2022/11/9 10:54
     */
    public function getMemberInfo()
    {
        // 检查用户
        $userRes = $this->checkUser();
        if ($userRes['errorCode'] == 1) $this->sendFail('用户不存在');
        $result = (new \app\common\model\service\LibMember())->getMemberInfo($this->user_id);
        $this->sendSuccess('查询成功', $result);
    }

    /**
     * Info: 获取配置值
     * Date: 2022/8/25 10:49
     */
    public function getGlobalConfigValue()
    {
        $key = input('key');
        $result = (new LibConfig())->findConfig(array('item_key' => $key));
        if ($key == 'matchmaker_introduce' || $key == 'promote_contents' || $key == 'stores_introduce' || $key == 'vip_contents') {
            $item_value = $result['data']['item_value'];
            $arr = explode("\n",$item_value);
            $result['data']['item_value'] = implode('<br/>',$arr);
        }
        $this->response = $result;
        $this->sendResponse();
    }

    /**
     * Info: 检查用户状态
     * Date: 2022/11/18 17:52
     */
    public function checkUserStateByOneYuan ()
    {
        // 检查用户
        $userRes = $this->checkUser();
        if ($userRes['errorCode'] == 1) $this->sendFail('用户不存在');
        $result = (new \app\common\model\service\LibOrder($userRes['data']))->paymentBeforeCheckUserStateByOneYuan();
        $this->response = $result;
        $this->sendResponse();
    }

    /**
     * Info: 一元订单
     * Date: 2022/11/8 11:43
     */
    public function createOneYuanOrder()
    {
        // 检查用户
        $userRes = $this->checkUser();
        if ($userRes['errorCode'] == 1) $this->sendFail('用户不存在');
        $result = (new \app\common\model\service\LibOrder($userRes['data']))->addOrderByOneYuanSeeVideo();
        $this->response = $result;
        $this->sendResponse();
    }

    /**
     * Info: vip租赁订单
     * Date: 2022/11/8 11:58
     */
    public function createVipOrder()
    {
        // 检查用户
        $userRes = $this->checkUser();
        if ($userRes['errorCode'] == 1) $this->sendFail('用户不存在');
        $result = (new \app\common\model\service\LibOrder($userRes['data']))->addOrderByVip();
        $this->response = $result;
        $this->sendResponse();
    }

    /**
     * Info: 视频认证订单
     * Date: 2022/11/8 13:39
     */
    public function createVipAuthOrder()
    {
        // 检查用户
        $userRes = $this->checkUser();
        if ($userRes['errorCode'] == 1) $this->sendFail('用户不存在');
        $result = (new \app\common\model\service\LibOrder($userRes['data']))->addOrderByVipAuth();
        $this->response = $result;
        $this->sendResponse();
    }

    /**
     * Info: 红娘认证订单
     * Date: 2022/11/8 13:39
     */
    public function createRedMotherAuthOrder()
    {
        // 检查用户
        $userRes = $this->checkUser();
        if ($userRes['errorCode'] == 1) $this->sendFail('用户不存在');
        $result = (new \app\common\model\service\LibOrder($userRes['data']))->addOrderByRedMotherAuth();
        $this->response = $result;
        $this->sendResponse();
    }

    /**
     * Info: vip套餐列表
     * Date: 2022/11/9 11:13
     */
    public function getVipList()
    {
        $model = new LibVip();
        $result = $model->findAllVip('', '', '', 'sort asc');
        $this->response = $result;
        $this->sendResponse();
    }

    /**
     * Info: 视频认证套餐列表
     * Date: 2022/11/9 11:13
     */
    public function getVideoAuthList()
    {
        $model = new LibVideoAuth();
        $result = $model->findAllVideoAuth('', '', '', 'id asc');
        $this->response = $result;
        $this->sendResponse();
    }

    /**
     * Info: 收藏与取消收藏
     * Date: 2022/11/9 10:18
     */
    public function saveCollect()
    {
        $input = [
            'user_id' => $this->user_id,
            'like_user_id' => input('like_user_id', 0),
        ];
        $userRes = $this->checkUser();
        if ($userRes['errorCode'] == 1) $this->sendFail('用户不存在');
        $model = new LibCollect();
        $checkRes = $model->goCheck($input);
        if ($checkRes['errorCode'] == 1) $this->sendFail($checkRes['errorInfo']);
        $findRes = $model->findCollect(['user_id' => $input['user_id'], 'like_user_id' => $input['like_user_id']]);
        if ($findRes['errorCode'] == 1) {
            $input['add_time'] = Common::getTime();
            $result = $model->addCollect($input);
            $result['errorInfo'] = '收藏成功';
        } else {
            $result = $model->deleteCollect($findRes['data']['id']);
            $result['errorInfo'] = '收藏已取消';
        }
        $this->response = $result;
        $this->sendResponse();
    }

    /**
     * Info: 浏览记录
     * Date: 2022/11/9 10:50
     */
    public function saveBrowseRecord()
    {
        $input = [
            'user_id' => $this->user_id,
            'like_user_id' => input('like_user_id', 0),
        ];
        $userRes = $this->checkUser();
        if ($userRes['errorCode'] == 1) $this->sendFail('用户不存在');
        $model = new LibBrowseHistory();
        $checkRes = $model->goCheck($input);
        if ($checkRes['errorCode'] == 1) $this->sendFail($checkRes['errorInfo']);
        $findHistoryRes = $model->findBrowseHistory($input);
        if ($findHistoryRes['errorCode'] == 0) {
            $result = $model->updateBrowseHistory($input,['add_time' => Common::getTime()]);
            $result['errorInfo'] = '更新成功';
        } else {
            $input['add_time'] = Common::getTime();
            $result = $model->addBrowseHistory($input);
            $result['errorInfo'] = '添加成功';
        }
        $this->response = $result;
        $this->sendResponse();
    }

    /**
     * Info: 更新转发数量
     * Date: 2022/11/9 11:02
     */
    public function updateShareCount()
    {
        $userRes = $this->checkUser();
        if ($userRes['errorCode'] == 1) $this->sendFail('用户不存在');
        $memberModel = new LibMember();
        $memberModel->increaseField(['user_id' => $this->user_id], 'share_num');
        $this->sendSuccess('更新成功', true);
    }

    /**
     * Info: 提交门店申请
     * Date: 2022/11/9 11:37
     */
    public function submitStoreApply()
    {
        $input = [
            'user_id' => $this->user_id,
            'username' => input('username', ''),
            'mobile' => input('mobile', '')
        ];
        $userRes = $this->checkUser();
        if ($userRes['errorCode'] == 1) $this->sendFail('用户不存在');
        if (strpos($userRes['data']['identity'],'4') !== false) {
            $this->sendFail('您已经是门店身份，不能再次申请了。');
        }
        $model = new LibStoresApply();
        $findRes = $model->findStoreApply(['user_id' => $this->user_id]);
        if ($findRes['errorCode'] == 0) {
            if ($findRes['data']['audit_state'] == 0) $this->sendFail('申请已提交，等待审核中');
            if ($findRes['data']['audit_state'] == 1) $this->sendFail('申请已通过，不能提交申请');
        }
        $input['add_time'] = Common::getTime();
        $result = $model->addStoreApply($input);
        $this->sendSuccess('提交成功', $result['data']);
    }

    /**
     * Info: 收藏记录/粉丝记录
     * Date: 2022/11/10 10:06
     */
    public function getCollectRecord()
    {
        $args = $this->getArgsList($this, ['user_id','is_fans']);
        $page = $this->getPageInfo();
        $where = [];
        if (isset($args['is_fans']) && $args['is_fans']) {//粉丝记录
            if (!empty($args['user_id'])) $where[] = "`like_user_id` = " . $args['user_id'];
        } else {//收藏记录
            $state = input('state', 1);
            if ($state == 1) {
                $where[] = "(`state` = '0' OR `state` = '1' OR `state` = '2')";//游客,普通会员,vip
            } else {
                $where[] = "FIND_IN_SET({$state},state)";//3红娘，4门店
            }
            if (!empty($args['user_id'])) $where[] = "`user_id` = " . $args['user_id'];
        }
        $result = (new LibCollect())->pagingCollect($page, implode(' AND ', $where));
        $userModel = new LibUser();
        $memberModel = new LibMember();
        $storeModel = new LibStore();
        foreach ($result['data']['dataList'] as &$item) {
            $item['user'] = [];
            $item['like_member'] = [];
            $findRes = $userModel->findUser(['id' => $item['user_id']], 'id,nick_name,account,head_img_url,add_time,identity');
            if ($findRes['errorCode'] == 0) {
                $findRes['data']['is_guest'] = 0;//是游客
                if (strpos($findRes['data']['identity'],'0') === false) {
                    $findRes['data']['is_guest'] = 1;//不是游客
                }
                $item['user'] = $findRes['data'];
                if ($findRes['data']['is_guest']) {
                    $findMemberRes = $memberModel->findMember(['user_id' => $item['user_id']]);
                    $item['like_member'] = $findMemberRes['data'];
                }
                if (strpos($findRes['data']['identity'],'4') !== false) {
                    $findStoreRes = $storeModel->findStore(['uid' => $item['user_id']]);
                    $item['user']['store'] = $findStoreRes['data'];
                }
            }
            $item['like_user'] = [];
            $findRes = $userModel->findUser(['id' => $item['like_user_id']], 'id,nick_name,account,head_img_url,add_time,identity');
            if ($findRes['errorCode'] == 0) {
                $findRes['data']['is_guest'] = 0;//是游客
                if (strpos($findRes['data']['identity'],'0') === false) {
                    $findRes['data']['is_guest'] = 1;//不是游客
                }
                $item['like_user'] = $findRes['data'];
                if (strpos($findRes['data']['identity'],'4') !== false) {
                    $findStoreRes = $storeModel->findStore(['uid' => $item['like_user_id']]);
                    $item['like_user']['store'] = $findStoreRes['data'];
                }
            }
            $item['vip_open_time'] = $item['vip_open_time'] ?date('Y-m-d H:i:s',$item['vip_open_time']) : 0;
        }
        $this->response = $result;
        $this->sendResponse();
    }

    /**
     * Info: 支付记录
     * Date: 2022/11/9 11:56
     */
    public function getPaymentRecord()
    {
        $args = $this->getArgsList($this, ['user_id','state']);
        $page = $this->getPageInfo();
        $where = [];
        $where[] = "`transaction_id` IS NOT NULL";
        if (!empty($args['user_id'])) $where[] = "`user_id` = " . $args['user_id'];
        if (isset($args['state']) && ($args['state'] == 0 || $args['state'] == 1 || $args['state'] == 2)) {
            if ($args['state'] == 0) $where[] = "`type` IN (0,1)";
            if ($args['state'] == 1) $where[] = "`type` = 2";
            if ($args['state'] == 2) $where[] = "`type` = 3";
        }
        $result = (new LibOrder())->pagingOrder($page, implode(' AND ', $where));
        $vipModel = new LibOrderVip();
        $refundModel = new LibOrderRefund();
        $week_time = 7*24*60*60;
        foreach ($result['data']['dataList'] as &$item) {
            if ($item['type'] == 1) {
                $findRes = $vipModel->findOrder(['order_id' => $item['id']]);
                $item['title'] = '开通会员';
                if ($findRes['errorCode'] == 0) {
                    $vipInfo = json_decode($findRes['data']['vip_info'], true);
                    $item['title'] = '开通会员 ' . $vipInfo['title'];
                }
            }
            if ($item['type'] == 0) $item['title'] = '视频单次付费';
            if ($item['type'] == 2) $item['title'] = '栏目认证会员';
            if ($item['type'] == 3) $item['title'] = '成为红娘';

            // 判断是否超过7天
            $add_time = strtotime($item['pay_time']);
            $diff_time = time() - $add_time;
            $item['more_7_day'] = 0;
            if (abs($diff_time) > $week_time) {
                $item['more_7_day'] = 1;
            }

            // 是否存在退款记录且已退款
            $item['is_refund'] = 0;
            if ($item['type'] > 1) {
                $type = $item['type'] == 3 ? 2 : 1;
                $findRefundRes = $refundModel->findRefund(['user_id' => $item['user_id'],'refund_state' => 1,'type' => $type]);
                if ($findRefundRes['errorCode'] == 0) {
                    $item['is_refund'] = 1;
                }
            }
        }

        $total_pay_amount = db('hfztcy_order')->where('user_id','=',$args['user_id'])->whereNotNull('transaction_id')->sum('pay_amount');
        $this->sendSuccess('查询成功',[
            [
                'total_pay_money' => $total_pay_amount,
                'result' => $result['data']
            ]
        ]);
    }

    /**
     * Info: 观看记录
     * Date: 2022/11/10 9:50
     */
    public function getVideoBrowseRecord()
    {
        $args = $this->getArgsList($this, ['user_id']);
        $page = $this->getPageInfo();
        $where = [];
        if (!empty($args['user_id'])) $where[] = "`user_id` = " . $args['user_id'];
        $result = (new LibBrowseHistory())->pagingBrowseHistory($page, implode(' AND ', $where));
        $videoModel = new LibUserVideoAuth();
        $userModel = new LibUser();
        foreach ($result['data']['dataList'] as &$item) {
            // 视频路径
            $item['video'] = [];
            $findRes = $videoModel->findUserVideoAuth(['user_id' => $item['like_user_id']]);
            if ($findRes['errorCode'] == 0) {
                $findRes['data']['video_url'] = ROOT_URL . '/' . str_replace('upload/','upload/sliceVideo/',$findRes['data']['video_url']);
                $item['video'] = $findRes['data'];
            }

            // 用户昵称，头像
            $item['like_user'] = [];
            $findRes = $userModel->findUser(['id' => $item['like_user_id']], 'id,nick_name,account,head_img_url,add_time');
            if ($findRes['errorCode'] == 0) {
                $item['like_user'] = $findRes['data'];
            }

            // 默认照片
            $item['user_img'] = null;
            if ($item['photo_list']) {
                $user_img_list = explode(',',$item['photo_list']);
                $item['photo_list'] = $user_img_list;
                $item['user_img'] = $user_img_list[0];
            }
        }
        $this->response = $result;
        $this->sendResponse();
    }

    /**
     * Info: 获取门店团队
     * Date: 2022/11/10 10:31
     */
    public function getStoreTeam()
    {
        $parent_id = input('parent_id',0);

        $page = $this->getPageInfo();
        $page['pageIndex'] ? $pageIndex = $page['pageIndex'] : $pageIndex = 1;
        $page['pageSize'] ? $pageSize = $page['pageSize'] : $pageSize = 10;
        $m = ($pageIndex - 1) * $pageSize;
        $n = $pageSize;

        $querySql = <<< SQL
SELECT b.*,a.parent_id,a.nick_name,a.head_img_url  
FROM `hfztcy_store` AS `b` 
LEFT JOIN `base_user` AS `a` ON `b`.`uid` = `a`.`id` 
WHERE `b`.`user_id` = {$parent_id} and `b`.`uid` != {$parent_id}
ORDER BY b.add_time DESC 
SQL;
        $sql = $querySql . " LIMIT {$m}, {$n}";
        $sqlAll = $querySql;
        $result['data']['dataList'] = Db::query($sql);
        $sql = "SELECT count(count_table.id) as total_record_num  from ( {$sqlAll} ) as count_table";
        $count = Db::query($sql);
        //如果之后1页，手动添加分页信息
        $result['data']['pageInfo']['current_page'] = $pageIndex;
        $result['data']['pageInfo']['first_page'] = 1;
        $result['data']['pageInfo']['prev_page'] = $pageIndex - 1;
        $result['data']['pageInfo']['next_page'] = $pageIndex + 1;
        $result['data']['pageInfo']['last_page'] = ceil($count[0]['total_record_num'] / $pageSize);
        $result['data']['pageInfo']['total_count'] = $count[0]['total_record_num'];
        $result['data']['pageInfo']['total_page'] = ceil($count[0]['total_record_num'] / $pageSize);
        $result['data']['pageInfo']['page_size'] = $pageSize;
        $result['data']['pageInfo']['all_pages'] = ceil($count[0]['total_record_num'] / $pageSize);
        $result['errorCode'] = 0;
        $result['errorInfo'] = '查询成功';
        $memberModel = new LibMember();
        foreach ($result['data']['dataList'] as &$item) {
            $res = $memberModel->findMember(['user_id' => $item['user_id']]);
            $item['is_userInfo'] = 0;
            if ($res['errorCode'] == 0) {
                $item['is_userInfo'] = 1;
                $item['userInfo'] = $res['data'];
            }
        }
        $this->response = $result;
        $this->sendResponse();
    }

    /**
     * Info: 会员团队
     * Date: 2022/11/10 10:20
     */
    public function getUserTeam()
    {
        $state = input('state','0');
        $identity = input('identity',0);
        $parent_id = input('parent_id','');
        $page = $this->getPageInfo();
        //$page['pageIndex'] ? $pageIndex = $page['pageIndex'] : $pageIndex = 1;
        $page['pageSize'] = 500;
        $where = [];
        // 个人详情页-会员
        if ($identity) {
            $where[] = "(FIND_IN_SET('1',identity) OR FIND_IN_SET('2',identity))";
        }
        // 会员团队
        if ($state == '0' || $state == '1' || $state == '2') {
            $where[] = "FIND_IN_SET('$state',identity)";
        }
        if ($parent_id != '') {
            $sql = <<< SQL
SELECT user_id FROM `hfztcy_member_distribute` WHERE `one_user_id` = {$parent_id}
SQL;
            $query = Db::query($sql);
            if ($query) {
                $userIds = array_column($query,'user_id');
                $userIds = implode(',',$userIds);
                // 栏目认证
                if ($state == '3') {
                    $sql = <<< SQL
SELECT user_id FROM `hfztcy_user` WHERE `user_id` IN ({$userIds}) AND `is_vip_video` > 0
SQL;
                    $query = Db::query($sql);
                    if ($query) {
                        $userIds = array_column($query,'user_id');
                        $userIds = implode(',',$userIds);
                        $where[] = "`id` IN ($userIds)";
                    } else {
                        $where[] = "`id` = ''";
                    }
                } else {
                    $where[] = "`id` IN ($userIds)";
                }
            } else {
                $where[] = "`id` = ''";
            }
        }
        if ($identity) {
            //echo implode(' AND ', $where);
        }
        $result = (new LibUser())->pagingUser2($page, implode(' AND ', $where));
        $memberModel = new LibMember();
        foreach ($result['data']['dataList'] as $key => &$item) {
            $res = $memberModel->findMember(['user_id' => $item['id']]);
            $item['is_userInfo'] = 0;
            if ($res['errorCode'] == 0) {
                if ($res['data']['is_disabled'] || $res['data']['audit_state'] == 2) {
                    unset($result['data']['dataList'][$key]);
                    continue;
                }
                $item['is_userInfo'] = 1;
                $item['userInfo'] = $res['data'];
            }
        }
        $result['data']['dataList'] = array_values($result['data']['dataList']);
        $this->response = $result;
        $this->sendResponse();
    }

    /**
     * Info: 红娘团队
     * Date: 2022/11/10 10:31
     */
    public function getRedMotherTeam()
    {
        $parent_id = input('parent_id',0);
        $page = $this->getPageInfo();
        $page['pageIndex'] ? $pageIndex = $page['pageIndex'] : $pageIndex = 1;
        $page['pageSize'] ? $pageSize = $page['pageSize'] : $pageSize = 10;
        $m = ($pageIndex - 1) * $pageSize;
        $n = $pageSize;

        $querySql = <<< SQL
SELECT a.* 
FROM `base_user` AS `a` 
    LEFT JOIN `hfztcy_member_distribute` AS `b` 
        ON `a`.`id` = `b`.`user_id` 
WHERE `b`.`pid` = {$parent_id} AND FIND_IN_SET(3,a.identity) 
ORDER BY a.add_time DESC
SQL;
        $sql = $querySql . " LIMIT {$m}, {$n}";
        $sqlAll = $querySql;
        $result['data']['dataList'] = Db::query($sql);
        $sql = "SELECT count(count_table.id) as total_record_num  from ( {$sqlAll} ) as count_table";
        $count = Db::query($sql);
        //如果之后1页，手动添加分页信息
        $result['data']['pageInfo']['current_page'] = $pageIndex;
        $result['data']['pageInfo']['first_page'] = 1;
        $result['data']['pageInfo']['prev_page'] = $pageIndex - 1;
        $result['data']['pageInfo']['next_page'] = $pageIndex + 1;
        $result['data']['pageInfo']['last_page'] = ceil($count[0]['total_record_num'] / $pageSize);
        $result['data']['pageInfo']['total_count'] = $count[0]['total_record_num'];
        $result['data']['pageInfo']['total_page'] = ceil($count[0]['total_record_num'] / $pageSize);
        $result['data']['pageInfo']['page_size'] = $pageSize;
        $result['data']['pageInfo']['all_pages'] = ceil($count[0]['total_record_num'] / $pageSize);
        $result['errorCode'] = 0;
        $result['errorInfo'] = '查询成功';
        $memberModel = new LibMember();
        foreach ($result['data']['dataList'] as &$item) {
            $res = $memberModel->findMember(['user_id' => $item['id']]);
            $item['is_userInfo'] = 0;
            if ($res['errorCode'] == 0) {
                $item['is_userInfo'] = 1;
                $item['userInfo'] = $res['data'];
            }
        }
        $this->response = $result;
        $this->sendResponse();
    }

    /**
     * Info: 获取评价列表
     * Date: 2022/11/9 11:45
     */
    public function getEvaluationList()
    {
        $args = $this->getArgsList($this, ['user_id', 'type']);
        $page = $this->getPageInfo();
        $where = [];
        $where[] = "`type` = {$args['type']}";
        if (!empty($args['user_id'])) $where[] = "`user_id` = " . $args['user_id'];
        $result = (new LibEvaluation())->pagingEvaluation($page, implode(' AND ', $where));
        $this->response = $result;
        $this->sendResponse();
    }

    /**
     * Info: 添加评价
     * Date: 2022/11/9 11:51
     */
    public function addEvaluation()
    {
        $input = [
            'user_id' => $this->user_id,
            'star_num' => input('star_num', ''),
            'img' => input('img', ''),
            'content' => input('content', ''),
            'type' => input('type', 0),
        ];
        $userRes = $this->checkUser();
        if ($userRes['errorCode'] == 1) $this->sendFail('用户不存在');
        $model = new LibEvaluation();
        //红娘或者门店每个星期只能评价一次
        $input['add_time'] = Common::getTime();
        $weeks = $this->getWeekRange($input['add_time']);
        $sql = <<< SQL
SELECT count(*) num FROM `hfztcy_evaluation` WHERE `user_id` = {$this->user_id} AND (`add_time` >= '{$weeks['sdate']}' AND `add_time` <= '{$weeks['edate']}')
SQL;
        $res = Db::query($sql);
        if ($res && $res[0]['num']) $this->sendFail('评价每星期只能提交一次');
        $result = $model->addEvaluation($input);
        $this->sendSuccess('提交成功', $result['data']);
    }

    /**
     * Info: 修改评价
     * Date: 2022/11/9 11:51
     */
    public function editEvaluation()
    {
        $input = [
            'user_id' => $this->user_id,
            'star_num' => input('star_num', ''),
            'img' => input('img', ''),
            'content' => input('content', ''),
            'type' => input('type', 0),
            'id' => input('id', 0),
        ];
        $userRes = $this->checkUser();
        if ($userRes['errorCode'] == 1) $this->sendFail('用户不存在');
        $model = new LibEvaluation();
        $findRes = $model->findEvaluation(['user_id' => $this->user_id]);
        if ($findRes['errorCode'] == 0 && $findRes['data']['id'] != $input['id']) {
            $this->sendFail('评价已存在');
        }
        $result = $model->updateEvaluation(['id' => $input['id']], $input);
        $this->sendSuccess('提交成功', $result['data']);
    }

    private function getWeekRange($date)
    {
        $ret = array();
        $timestamp = strtotime($date);
        $w = strftime('%u', $timestamp);
        $ret['sdate'] = date('Y-m-d 00:00:00', $timestamp - ($w - 1) * 86400);
        $ret['edate'] = date('Y-m-d 23:59:59', $timestamp + (7 - $w) * 86400);
        return $ret;
    }

    /**
     * Info: 修改会员状态
     * Date: 2022/11/11 17:42
     */
    public function updateMemberState()
    {
        $userRes = $this->checkUser();
        if ($userRes['errorCode'] == 1) $this->sendFail('用户不存在');
        $model = new LibMember();
        $model->updateMember(['user_id' => $this->user_id], ['is_disabled' => input('is_disabled', 1)]);
        $this->sendSuccess('修改成功', true);
    }

    /**
     * Info: 门店-我的订单列表
     * Date: 2022/11/10 8:59
     */
    public function getStoreOrderByShooteVcr()
    {
        $args = $this->getArgsList($this, ['user_id', 'is_pick_up']);
        $page = $this->getPageInfo();
        $storeModel = new LibStore();
        $findRes = $storeModel->findStore(['uid' => $args['user_id']]);
        $store_id = 0;
        if ($findRes['errorCode'] == 0) $store_id = $findRes['data']['id'];
        $where = [];
        $where[] = "`transaction_id` is not null";
        if (!empty($store_id)) $where[] = "`store_id` = " . $store_id;
        if ($args['is_pick_up'] != '' && in_array($args['is_pick_up'], [0, 1])) $where[] = "`is_pick_up` = " . $args['is_pick_up'];
        $result = (new LibOrder())->pagingOrderByStoreVcr($page, implode(' AND ', $where));
        foreach ($result['data']['dataList'] as &$item) {
            $item['vip_open_time'] = $item['vip_open_time'] ? date('Y-m-d H:i:s',$item['vip_open_time']) : 0;
        }
        $this->response = $result;
        $this->sendResponse();
    }

    /**
     * Info: 门店-拍摄状态更新
     * Date: 2022/11/24 15:21
     */
    public function updateStoreVideoShooteState ()
    {
        $userRes = $this->checkUser();
        if ($userRes['errorCode'] == 1) $this->sendFail('用户不存在');
        $args = $this->getArgsList($this, ['user_id','order_id']);
        $model = new LibOrderVipAuth();
        $findOrderRes = $model->findOrder(['order_id' => $args['order_id']]);
        if ($findOrderRes['errorCode'] == 0) {
            $model->updateOrder(['order_id' => $args['order_id']], ['is_pick_up' => 1,'pick_up_complete_time' => Common::getTime()]);
        }
        $this->sendSuccess('更新成功',false);
    }

    /**
     * Info: 疑问解答
     * Date: 2022/9/27 15:45
     */
    public function getQuestionList()
    {
        $where = [];
        $page = $this->getPageInfo();
        $model = new LibQuestions();
        $result = $model->pagingQuestion($page, implode(' AND ', $where));
        $this->response = $result;
        $this->sendResponse();
    }

    /**
     * Info: 提交留言
     * Date: 2022/11/11 17:54
     */
    public function submitMessage()
    {
        $input = [
            'user_id' => $this->user_id,
            'content' => input('content', ''),
            'type' => input('type', 0),
        ];
        $userRes = $this->checkUser();
        if ($userRes['errorCode'] == 1) $this->sendFail('用户不存在');
        $model = new LibMessage();
        $checkRes = $model->goCheck($input);
        if ($checkRes['errorCode'] == 1) $this->sendFail($checkRes['errorInfo']);
        $input['add_time'] = Common::getTime();
        $model->addMessage($input);
        $this->sendSuccess('留言提交成功', true);
    }

    /**
     * Info: 获取留言记录
     * Date: 2022/8/17 9:02
     */
    public function getMessageRecords()
    {
        $this->checkUser();
        $page = $this->getPageInfo();
        $model = new LibMessage();
        $where[] = "`user_id` = {$this->user_id}";
        $result = $model->pagingMessage($page, implode(' AND ', $where));
        $this->response = $result;
        $this->sendResponse();
    }

    /**
     * Info: 收益明细
     * Date: 2022/8/17 9:02
     */
    public function getMyCommissionRecords()
    {
        $this->checkUser();
        $where = [];
        $state = input('state');
        $isStore = input('isStore',0);
        if ($isStore) {
            $sql = "SELECT uid FROM `hfztcy_store` WHERE `user_id` = {$this->user_id} and `uid` != {$this->user_id};";
            $result = Db::query($sql);
            if ($result) {
                $ids = implode(',',array_values($result[0]));
                $where[] = "`user_id` IN ({$ids})";
            } else {
                $where[] = "`user_id` = ''";
            }
        } else {
            $where[] = "`user_id` = {$this->user_id}";
        }
        $page = $this->getPageInfo();
        $model = new LibBalanceRecords();
        if ($state == 0 || $state == 1 || $state == 2) $where[] = "`zj_state` = {$state}";
        $result = $model->pagingCommissionRecords($page, implode(' AND ', $where));
        $storeModel = new LibStore();
        foreach ($result['data']['dataList'] as &$item)
        {
            if ($isStore)
            {
                $findStoreRes = $storeModel->findStore(['uid' => $item['user_id']]);
                if ($findStoreRes['errorCode'] == 0)
                {
                    $findStoreRes['data']['storeimgs'] = ROOT_URL.'/'.$findStoreRes['data']['storeimgs'];
                    $item['store'] = $findStoreRes['data'];
                    $name = $findStoreRes['data']['title'];
                    $item['describe'] = str_replace('可得佣金',$name.'可得佣金',$item['describe']);
                }
            } else {
                $name = empty($item['username']) ? $item['nick_name'] : $item['username'];
                $item['describe'] = str_replace('可得佣金',$name.'可得佣金',$item['describe']);
            }
        }
        $this->response = $result;
        $this->sendResponse();
    }

    /**
     * Info: 提现明细
     * Date: 2022/6/22 15:47
     */
    public function getMyWithdrawRecords()
    {
        $user_id = input('user_id', 0);
        $this->checkUser();
        $page = $this->getPageInfo();
        $where[] = "`user_id` = {$user_id}";
        $where[] = "`audit_status` = 1";
        $model = new LibWithdrawalApply();
        $result = $model->pagingWithdrawalApply($page, implode(' AND ', $where));
        foreach ($result['data']['dataList'] as &$item) {
            $item['add_time'] = date('Y-m-d H:i', strtotime($item['add_time']));
            $item['audit_time'] = date('Y-m-d H:i', strtotime($item['audit_time']));
        }
        $total_pay_amount = db('hfztcy_withdrawal_apply')->where('user_id','=',$user_id)->where('audit_status','=',1)->sum('amount');
        $this->sendSuccess('查询成功',[
            'total_amount' => $total_pay_amount,
            'result' => $result['data']
        ]);
    }

    /**
     * Info: 添加提现账户
     * Date: 2022/7/25 19:21
     */
    public function addMyWithdrawalAccount()
    {
        $args = $this->getArgsList($this, ['user_id', 'username', 'account', 'bankname', 'type'], false);
        $userRes = $this->checkUser();
        if ($userRes['errorCode'] == 1) $this->sendFail('用户不存在');
        $model = new LibWithdrawalAccounts();
        $checkRes = $model->goCheck($args);
        if ($checkRes['errorCode'] == 1) $this->sendFail($checkRes['errorInfo']);
        $findRes = $model->findWithdrawalAccount(['user_id' => $this->user_id, 'username' => $args['username'], 'account' => $args['account'], 'type' => $args['type']]);
        if ($findRes['errorCode'] == 0) $this->sendFail('请勿重复提交');
        $args['add_time'] = Common::getTime();
        $model->addWithdrawalAccount($args);
        $this->sendSuccess('添加成功', true);
    }

    /**
     * Info: 修改提现账户
     * Date: 2022/7/25 19:21
     */
    public function editMyWithdrawalAccount()
    {
        $args = $this->getArgsList($this, ['id', 'user_id', 'username', 'account', 'bankname', 'type'], false);
        $userRes = $this->checkUser();
        if ($userRes['errorCode'] == 1) $this->sendFail('用户不存在');
        $model = new LibWithdrawalAccounts();
        $checkRes = $model->goCheck($args, 'edit');
        if ($checkRes['errorCode'] == 1) $this->sendFail($checkRes['errorInfo']);
        $findRes = $model->findWithdrawalAccount(['user_id' => $this->user_id, 'username' => $args['username'], 'account' => $args['account'], 'type' => $args['type']]);
        if ($findRes['errorCode'] == 0 && $args['id'] != $findRes['data']['id']) $this->sendFail('请勿重复提交');
        $id = $args['id'];
        unset($args['id']);
        $model->updateWithdrawalAccount(['id' => $id], $args);
        $this->sendSuccess('修改成功', true);
    }

    /**
     * Info: 删除提现账户
     * Date: 2022/7/25 19:21
     */
    public function deleteMyWithdrawalAccount()
    {
        $args = $this->getArgsList($this, ['id', 'user_id'], false);
        $userRes = $this->checkUser();
        if ($userRes['errorCode'] == 1) $this->sendFail('用户不存在');
        $model = new LibWithdrawalAccounts();
        $checkRes = $model->goCheck($args, 'del');
        if ($checkRes['errorCode'] == 1) $this->sendFail($checkRes['errorInfo']);
        $findRes = $model->findWithdrawalAccount(['id' => (int)$args['id'], 'user_id' => $this->user_id]);
        if ($findRes['errorCode'] == 0) {
            $model->deleteWithdrawalAccount($args['id']);
            $this->sendSuccess('删除成功', true);
        }
        $this->sendSuccess('修改失败', false);
    }

    /**
     * Info: 提现账户信息
     * Date: 2022/7/26 15:59
     */
    public function getMyWithdrawalAccount()
    {
        $id = input('id');
        $userRes = $this->checkUser();
        if ($userRes['errorCode'] == 1) $this->sendFail('用户不存在');
        $model = new LibWithdrawalAccounts();
        $result = $model->findWithdrawalAccount(['id' => $id, 'user_id' => $this->user_id]);
        $this->sendSuccess('查询成功', $result['data']);
    }

    /**
     * Info: 获取提现账户集合
     * Date: 2022/7/25 18:07
     */
    public function pagingGetMyWithdrawalAccounts()
    {
        $page = $this->getPageInfo();
        $page['pageIndex'] ? $pageIndex = $page['pageIndex'] : $pageIndex = 1;
        $page['pageSize'] ? $pageSize = $page['pageSize'] : $pageSize = 10;
        $m = ($pageIndex - 1) * $pageSize;
        $n = $pageSize;

        $querySql = <<< SQL
SELECT a.*,b.nick_name 
FROM `hfztcy_withdrawal_accounts` AS `a` 
LEFT JOIN `base_user` `b` ON `a`.`user_id`=`b`.`id` 
WHERE `a`.`user_id` = {$this->user_id} 
ORDER BY a.add_time ASC 
SQL;
        $sql = $querySql . " LIMIT {$m}, {$n}";
        $sqlAll = $querySql;
        $result['data']['dataList'] = Db::query($sql);
        $sql = "SELECT count(count_table.id) as total_record_num  from ( {$sqlAll} ) as count_table";
        $count = Db::query($sql);
        //如果之后1页，手动添加分页信息
        $result['data']['pageInfo']['current_page'] = $pageIndex;
        $result['data']['pageInfo']['first_page'] = 1;
        $result['data']['pageInfo']['prev_page'] = $pageIndex - 1;
        $result['data']['pageInfo']['next_page'] = $pageIndex + 1;
        $result['data']['pageInfo']['last_page'] = ceil($count[0]['total_record_num'] / $pageSize);
        $result['data']['pageInfo']['total_count'] = $count[0]['total_record_num'];
        $result['data']['pageInfo']['total_page'] = ceil($count[0]['total_record_num'] / $pageSize);
        $result['data']['pageInfo']['page_size'] = $pageSize;
        $result['data']['pageInfo']['all_pages'] = ceil($count[0]['total_record_num'] / $pageSize);
        $result['errorCode'] = 0;
        $result['errorInfo'] = '查询成功';

        echo json_encode($result);
        die();
    }

    /**
     * Info: 会员提现
     * Date: 2022/7/25 18:19
     */
    public function memberWithdrawalCommission()
    {
        $args = $this->getArgsList($this, ['user_id', 'amount', 'account_id'], false);
        // 简单的表单验证
        $model = new LibWithdrawalApply();
        $checkRes = $model->goCheck($args);
        if ($checkRes['errorCode'] == 1) $this->sendFail($checkRes['errorInfo']);
        $amount = (float)$args['amount'];
        $account_id = (int)$args['account_id'];

        // 提现手续费
        $configModel = new LibConfig();
        $findConfigRes = $configModel->findConfig(['item_key' => 'withdrawal_service_fee']);
        $withdrawal_service_fee = (float)$findConfigRes['data']['item_value'];
        //if (!$withdrawal_service_fee) $this->sendFail('平台未设置手续费');
        // 检查用户
        $userRes = $this->checkUser();
        if ($userRes['errorCode'] == 1) $this->sendFail('用户不存在');
        // 检查用户是否注册
        $memberModel = new LibMember();
        $findRes = $memberModel->findMember(['user_id' => $args['user_id']]);
        if ($findRes['errorCode'] == 1) $this->sendFail('用户未注册');
        // 检查用户余额
        $commission = floatval($findRes['data']['balance']);
        if ($commission <= 0 || $commission < $amount) $this->sendFail('余额不足');
        // 佣金满足最低标准，方可提现
        $configRes = $configModel->findConfig(['item_key' => 'withdrawal_lines']);
        if ($configRes['errorCode'] == 0) {
            if ($amount < $configRes['data']['item_value']) $this->sendFail('提现金额不足' . $configRes['data']['item_value'] . '，不允许提现。');
        }
        // 检查用户提现账号
        $userAccountModel = new LibWithdrawalAccounts();
        $userAccountRes = $userAccountModel->findWithdrawalAccount(['user_id' => $this->user_id, 'id' => $account_id]);
        if ($userAccountRes['errorCode'] == 1) $this->sendFail('提现账号不存在');

        // 手续费
        $withdrawal_service_commission = $amount * $withdrawal_service_fee;
        // 实际拨款金额
        $trans_money = $amount - $withdrawal_service_commission;

        Db::startTrans();
        try {
            // 添加提现记录
            $insert = [];
            $insert['user_id'] = $this->user_id;
            $insert['account_id'] = $account_id;
            $insert['amount'] = $amount;
            $insert['service_fee'] = $withdrawal_service_commission;
            $insert['trans_money'] = $trans_money;
            $insert['add_time'] = Common::getTime();
            $result = $model->addWithdrawalApply($insert);
            if ($result['errorCode'] == 0) {
                // 扣除用户佣金
                $memberModel->decreaseField(['user_id' => $this->user_id], 'balance', $amount);
                (new LibUser())->decreaseField(['id' => $this->user_id], 'balance', $amount);
                // 放入冻结字段
                $memberModel->updateMember(['user_id' => $this->user_id], ['freeze_balance' => $amount]);
                // 添加余额变动记录
                $data = [];
                $data['user_id'] = $this->user_id;
                $data['before_balance'] = $findRes['data']['balance'];
                $data['amount'] = $amount;
                $data['add_time'] = Common::getTime();
                $data['is_income'] = 1;
                $data['info'] = '用户主动申请提现余额';
                $balanceChangeModel = new LibBalanceChangeRecords();
                $balanceChangeModel->addBalanceChangeRecords($data);

                Db::commit();
                $this->sendSuccess('提现申请已提交，等待平台审核',false);
            } else {
                Db::rollback();
                $this->sendSuccess('提现申请失败',false);
            }
        } catch (Exception $exception) {
            Db::rollback();
            $this->sendFail($exception->getMessage());
        }
    }

    /**
     * Info: 生成海报
     * Date: 2022/8/2 8:52
     */
    public function generatePosters()
    {
        //$shareLink = input('shareLink');
        $user_id = input('user_id');
        $memberModel = new LibMember();
        $findMemberRes = $memberModel->findMember(['user_id' => $user_id]);
        if ($findMemberRes['errorCode'] == 0) {
            if ($findMemberRes['data']['poster_img_url'] && $findMemberRes['data']['poster_qrcode_url']) {
                $this->sendSuccess('success', [
                    'posterImgPath' => $findMemberRes['data']['poster_img_url'],
                    //'shareLink' => $shareLink
                ]);
            }
        }
        $getParamQRCodeUrl = UtilQRcode::getParamQRcode($user_id,2);
        $obj = new LibPoster();
        $res = $obj->generatePosters($getParamQRCodeUrl);
        if ($res['errorCode'] == 1) {
            $this->sendFail($res['errorInfo']);
        }
        $poster_img_url = str_replace(ROOT_PATH.'public',ROOT_URL,$res['data']);
        $poster_qrcode_url = str_replace('posters','qrcode',$poster_img_url);
        $poster_qrcode_url = str_replace('.png','original_.png',$poster_qrcode_url);
        $memberModel->updateMember(['user_id' => $user_id],['poster_img_url' => $poster_img_url,'poster_qrcode_url' => $poster_qrcode_url]);
        $this->sendSuccess('success', [
            'posterImgPath' => $poster_img_url,
            //'shareLink' => $shareLink
        ]);
    }

    /**
     * Info: 下载海报图
     * Date: 2022/11/17 9:42
     */
    public function download()
    {
        $path = input('path');
        list($body, $ext) = explode('.' , $path);
        $path = str_replace(ROOT_URL, '', $path);
        $file_dir = ROOT_PATH . 'public' . DS . $path;
        // 检查文件是否存在
        if (!file_exists($file_dir)) {
            echo json_encode(Common::errorArray(1, 'fail', false));
        } else {
            // 打开文件
            $file1 = fopen($file_dir, "r");
            // 输入文件标签
            Header("Content-type: application/octet-stream");
            Header("Accept-Ranges: bytes");
            Header("Accept-Length:" . filesize($file_dir));
            Header("Content-Disposition: attachment;filename=" . date('YmdHis') . rand(1, 999) . '.' . $ext);
            ob_clean();     // 重点！！！
            flush();        // 重点！！！！可以清除文件中多余的路径名以及解决乱码的问题：
            //输出文件内容
            //读取文件内容并直接输出到浏览器
            echo fread($file1, filesize($file_dir));
            fclose($file1);
            exit();
        }
    }

    /**
     * Info: 获取微信配置
     * Date: 2022/11/22 8:49
     */
    public function getWxConfig ()
    {
        $result = JsSdk::getSignPackage(input('url',''));
        $this->sendSuccess('微信配置',$result);
    }

    /**
     * Info: 获取地址根据GPS
     * Date: 2022/11/23 10:20
     */
    public function getAddressByGPS ()
    {
        $lat = input('lat','');
        $lng = input('lng','');
        $api = "https://apis.map.qq.com/ws/geocoder/v1/?coord_type=5&get_poi=0&output=json&key=VXABZ-IHOKD-YLM4G-HXJUN-UMZNK-N3BCV&location={$lat}%2C{$lng}";
        $result = file_get_contents($api);
        $this->sendSuccess('解析成功',json_decode($result,true));
    }

    /**
     * Info: 获取门店列表
     * Date: 2022/11/23 10:20
     */
    public function getStoreList ()
    {
        $lat = input('lat','31.82057');
        $lng = input('lng','117.22901');
        $title = input('title','');
        $this->checkUser();
        $page = $this->getPageInfo();
        $model = new LibStore();
        //$where[] = "`user_id` > 0";
        $where[] = "`state` = 0";
        if (!empty($title)) $where[] = "`title` like '%".$title."%'";
        $memberModel = new LibMember();
        $findMemberRes = $memberModel->findMember(['user_id' => $this->user_id]);
        if ($findMemberRes['errorCode'] == 0) {
            $lat = $findMemberRes['data']['lat'] ?: '31.82057';
            $lng = $findMemberRes['data']['lng'] ?: '117.22901';
        }
        $result = $model->pagingStoreListByApi($page, implode(' AND ', $where),$lat,$lng);
        foreach ($result['data']['dataList'] as &$item) {
            $item['user_info'] = [];
            if ($item['uid']) {
                $findUserRes = $memberModel->findMemberToUser($item['uid']);
                if ($findUserRes['errorCode'] == 0) {
                    $item['user_info'] = $findUserRes['data'];
                }
            }
            $item['distance'] = $item['distance']/1000;
            $item['distance'] = sprintf('%.2f',$item['distance']);
        }
        $this->response = $result;
        $this->sendResponse();
    }

    /**
     * Info: 统计用户余额
     * Date: 2022/11/23 10:20
     */
    public function getAmountByMemberBalance ()
    {
        $userRes = $this->checkUser();
        if ($userRes['errorCode'] == 1) $this->sendFail('用户不存在');
        $memberModel = new LibMember();
        $findMemberRes = $memberModel->findMember(['user_id' => $this->user_id]);
        $total_balance = 0;
        $balance = 0;
        $commission = 0;
        $balance_history = 0;
        if ($findMemberRes['errorCode'] == 0) {
            $total_balance = $findMemberRes['data']['total_balance'];//累计佣金
            $balance = $findMemberRes['data']['balance'];//可提现佣金
            $commission = $findMemberRes['data']['commission'];//冻结佣金
            $shixiaoCommission = db('hfztcy_commission_records')->where('user_id','=',$this->user_id)->where('zj_state','=',2)->sum('amount');//已失效佣金
            $total_pay_amount = db('hfztcy_withdrawal_apply')->where('user_id','=',$this->user_id)->where('audit_status','=',1)->sum('amount');
            $balance_history = $total_pay_amount;
        }
        $this->sendSuccess('查询成功',[
            'total_balance' => $total_balance,
            'balance' => $balance,
            'commission' => $commission?:'0.00',
            'shixiaoCommission' => $shixiaoCommission?:'0.00',
            'balance_history' => $balance_history?:'0.00',
        ]);
    }

    /**
     * Info: 订单退款
     * Date: 2022/11/23 10:20
     */
    public function orderRefund ()
    {
        $userRes = $this->checkUser();
        if ($userRes['errorCode'] == 1) $this->sendFail('用户不存在');
        $memberModel = new LibMember();
        $findMemberRes = $memberModel->findMember(['user_id' => $this->user_id]);
        if ($findMemberRes['errorCode'] == 1) $this->sendFail('用户未注册');
        $refundModel = new LibOrderRefund();
        $code = $refundModel->generateOrderNum();
        $findRefundRes = $refundModel->findRefund(['user_id' => $this->user_id,'type' => input('type',0)]);
        if ($findRefundRes['errorCode'] == 0) if ($findRefundRes['data']['audit_state'] == 1 && $findRefundRes['data']['refund_state'] == 1) $this->sendFail('已退款');
        if ($findRefundRes['data']['type'] == 0) {
            $orderSubModel = new LibOrderRedMother();
            $findOrderSubRes = $orderSubModel->findOrder(['user_id' => $this->user_id]);
            if ($findOrderSubRes['errorCode'] == 1) $this->sendFail('用户未支付红娘费用');
        } else {
            $orderSubModel = new LibOrderVipAuth();
            $findOrderSubRes = $orderSubModel->findOrder(['user_id' => $this->user_id]);
            if ($findOrderSubRes['errorCode'] == 1) $this->sendFail('用户未支付栏目认证费用');
        }
        $orderModel = new LibOrder();
        $findOrderRes = $orderModel->findOrder(['id' => $findOrderSubRes['data']['order_id']]);
        $add_time = strtotime($findOrderRes['data']['pay_time']);
        $diff_time = time() - $add_time;
        $week_time = 7 * 24 * 60 * 60;
        if (abs($diff_time) > $week_time) $this->sendFail('超过7天不能退款');
        if ($findRefundRes['errorCode'] == 1) {
            $refundModel->addRefund([
                'code' => $code,
                'user_id' => $this->user_id,
                'add_time' => Common::getTime(),
                'type' => input('type',0)
            ]);
        } else {
            $refundModel->updateRefund(['id' => $findRefundRes['data']['id']], [
                'code' => $code,
                'user_id' => $this->user_id,
                'add_time' => Common::getTime(),
                'type' => input('type',0)
            ]);
        }
        $this->sendSuccess('申请已提交，等待平台审核',false);
    }

    /**
     * Info: 获取视频栏目
     * Date: 2023/1/13 17:06
     */
    public function getVideoCategoryList ()
    {
        $collectModel = new LibCollectCategory();
        $page = $this->getPageInfo();

        $where = [];

        // 展示，我收藏的栏目视频
        $user_id = input('like_user_id','');
        if ($user_id) {
            $categoryCollectModel = new LibCollectCategory();
            $findCategoryRes = $categoryCollectModel->findAllCollect(['user_id' => $user_id]);
            if ($findCategoryRes['errorCode'] == 0) {
                $videoIds = array_column($findCategoryRes['data'],'like_user_id');
                $videoIds = implode(',',$videoIds);
                $where[] = "`id` IN ({$videoIds})";
            }
        }

        $model = new LibVideoCategory();
        $result = $model->pagingVideoCategory($page,implode(' AND ',$where));
        $configModel = new LibConfig();
        $findConfigRes = $configModel->findConfig(['item_key' => 'category_posters_img']);
        $category_posters_img = $findConfigRes['data']['item_value'];
        $findConfigRes = $configModel->findConfig(['item_key' => 'platform_mobile']);
        $platform_mobile = $findConfigRes['data']['item_value'];
        foreach ($result['data']['dataList'] as &$item) {
            $item['video_url'] = str_replace('upload/','upload/sliceVideo/',$item['video_url']);
            $item['video_img'] = $category_posters_img;
            $item['mobile'] = $platform_mobile;
            // 是否已收藏
            $item['is_collect'] = 0;
            $res = $collectModel->findCollect(['user_id' => $this->user_id,'like_user_id' => $item['id']]);
            if ($res['errorCode'] == 0) {
                $item['is_collect'] = 1;
            }
            // 喜欢数/粉丝数
            $item['like_num'] = 0;
            if (isset($item['id']) && $item['id']) {
                $sql = <<< SQL
SELECT count(*) as num FROM `hfztcy_collect_category` WHERE `like_user_id` = {$item['id']}
SQL;
                $res = Db::query($sql);
                if ($res) {
                    $item['like_num'] = $res[0]['num'];
                }
            }
        }
        $this->response = $result;
        $this->sendResponse();
    }

    /**
     * Info: 栏目视频收藏与取消收藏
     * Date: 2022/11/9 10:18
     */
    public function saveVideoCategoryCollect()
    {
        $input = [
            'user_id' => $this->user_id,
            'like_user_id' => input('like_user_id', 0),
        ];
        $userRes = $this->checkUser();
        if ($userRes['errorCode'] == 1) $this->sendFail('用户不存在');
        $model = new LibCollectCategory();
        $checkRes = $model->goCheck($input);
        if ($checkRes['errorCode'] == 1) $this->sendFail($checkRes['errorInfo']);
        $findRes = $model->findCollect(['user_id' => $input['user_id'], 'like_user_id' => $input['like_user_id']]);
        if ($findRes['errorCode'] == 1) {
            $input['add_time'] = Common::getTime();
            $result = $model->addCollect($input);
            $result['errorInfo'] = '收藏成功';
        } else {
            $result = $model->deleteCollect($findRes['data']['id']);
            $result['errorInfo'] = '收藏已取消';
        }
        $this->response = $result;
        $this->sendResponse();
    }

    /**
     * Info: 获取用户海报
     * Date: 2023/2/2 11:05
     */
    public function getUserPoster ()
    {
        $findMemberRes = (new LibMember())->findMember(['user_id' => $this->user_id]);
        if ($findMemberRes['errorCode'] == 0) {
            $poster = $findMemberRes['data']['poster_img_url'];
            if (!$findMemberRes['data']['poster_qrcode_url']) {
                $qrcode = str_replace('posters','qrcode',$poster);
                $qrcode = str_replace('.png','original_.png',$qrcode);
            } else {
                $qrcode = $findMemberRes['data']['poster_qrcode_url'];
            }
            $this->sendSuccess('返回成功',[
                'poster_img_url' => $poster,
                'poster_qrcode_url' => $qrcode
            ]);
        }
        $this->sendFail('没有生成海报');
    }
}